<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/5/6
 * Time: 9:27
 */

namespace app\api\controller\shop;

use app\admin\model\ShopRelationCategory;
use app\api\controller\HomeCommon;
use app\api\model\Config;
use app\common\controller\UploadFile;
use app\lib\exception\ExistException;
use app\lib\exception\FailedException;
use app\lib\exception\NotFoundException;
use app\lib\exception\ParameterException;
use app\Validate\CreateShopValidate;
use app\Validate\PageMustValidate;
use app\Validate\SourceValidate;
use Payment\Client\Charge;
use Payment\Common\PayException;
use think\Db;
use think\Exception;
use think\Request;


class Shop extends HomeCommon
{
    /**
     * 查询用户的商家申请状态
     * @param Request $request
     * @return \think\response\Json
     */
    public function shopApplyStatus(Request $request){
        $post = $request->post();
        $where = [
            ['user_id',"eq",$post['user_id']],
        ];
        $balance = 0;
        $apply_status = -1;//1表示可以申请
        $result = (new \app\api\model\Shop())->findOne($where,"id,status,pay_money");//如果没有则可以提交
        if(!empty($result)){
          $apply_status = $result['status'];
          $balance = $result['pay_money'];
          if($result['status']==-1){
              $apply_status = -2;
          }
        }
        return writeJson(200,['apply_status'=>$apply_status,'balance'=>$balance]);
    }

    /**
     * 商家注册上传图片
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     */
    public function shopUpload(Request $request){

//        //定义是哪个目录
            $directory = "shop_register";
            $file = $_FILES['file'];
            // 创建时间目录
            $dir = $directory.'/'.date('Ymd');
            $path = './uploads/'.$dir.'/';
            if(!is_dir($path)){
                mkdir($path, 0777, true);
            }
            $upload = new UploadFile(true,$path, array('jpg', 'jpeg', 'png'));
            $path = $upload->upload_file($file);
            if($path){
                $path = ltrim($path,'.');
                return writeJson(200,[
                    'path' => $path
                ]);
            }else{
                throw new FailedException([
                    'msg' => $upload->get_msg()
                ]);
            }

    }
    /**
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     */
    //查询商家分类
    public function shopCategory(Request $request)
    {
        (new PageMustValidate())->goCheck();
        $where = [];
        $post = $request->post();
        $where['page'] = $post['page'];
        $dataList = (new \app\api\model\ShopCategory())->wechatListTotal($where, "id,category", "id desc", $post['page_number']);
        return writeJson(200, $dataList);
    }

    /**
     * 商家创建
     * @param Request $request
     * @return \think\response\Json
     * @throws Exception
     * @throws \app\lib\exception\ParameterException
     */
    public function shopCreate(Request $request){
        (new CreateShopValidate())->goCheck();
        $shopInfo = $request->post();
        $shopInfo['number'] = getRandNumber(8);//商家编码
        $category = $shopInfo['category'];
        unset($shopInfo['category']);
        $relationData = [];
        $where = [
            ['user_id',"eq",$shopInfo['user_id']],
        ];
        $result = (new \app\api\model\Shop())->findOne($where,"status");//如果没有则可以提交
        if($result&&$result>=0){
            throw new FailedException([
                'msg' => '您已提交申请，等待后台处理!'
            ]);
        }
        $check_phone = (new \app\admin\model\Shop())->where([
            [
                'phone','eq',$shopInfo['phone']
            ]
        ])->field('status,id')->find();
        if($check_phone['status']==-1){
            (new \app\admin\model\Shop())->where([
                [
                    'phone','eq',$shopInfo['phone']
                ]
            ])->delete();
        }
        try{
            Db::startTrans();
            $existShop = (new \app\admin\model\Shop())->searchShopByPhone($shopInfo['phone']);
            if(!empty($existShop)){
                throw new ExistException([
                    'msg' => '商家已存在'
                ]);
            }else{
                $shopInfo['out_trade_no'] = (new \app\api\model\Shop())->createOutTradeNo("S");
                $shopInfo['pay_money'] = (new Config())->findOne([['k','eq','shop_bond']],'v');
                $shop =  (new \app\admin\model\Shop())->createShop($shopInfo);
                if(!empty($shop)){
                    $shopId = $shop->id;
                    if(!isset($category)||!is_array($category)){
                        Db::rollback();
                        throw new FailedException(['msg'=>$category]);
                    }
                    foreach ($category as $value){
                        $data = [
                            'shop_id' => $shopId,
                            'category_id' =>$value
                        ];
                        array_push($relationData,$data);
                    }
                    $relation = (new ShopRelationCategory())->saveAll($relationData);

                    if(!empty($relation)){
                        Db::commit();
                        return writeJson(200,[]);
                    }else{
                        Db::rollback();
                        throw new FailedException([
                            'msg' => '新增商家失败，请重试'
                        ]);
                    }
                }else{
                    Db::rollback();
                    throw new FailedException([
                        'msg' => '新增商家失败，请重试'
                    ]);
                }
            }
        }catch (Exception $exception){
            Db::rollback();
            throw  $exception;
        }

    }

    /**
     * 商家支付
     * @param Request $request
     * @throws \app\lib\exception\ParameterException
     */
    public function shopPay(Request $request)
    {
        (new SourceValidate())->goCheck();

        $post = $request->post();
        if (!isset($post['pay_style'])) {
            throw new ParameterException(['msg' => '缺少支付方式']);
        }
        $where = [
            ['user_id', 'eq', $post['user_id']],
            ['status', 'eq', 1]
        ];
        $shop = (new \app\api\model\Shop())->findOne($where);
        if (!$shop) {
            throw new NotFoundException(['msg' => '您暂未有待支付的商家信息']);
        }
        if(TestPrice==1){
            $shop['pay_money'] = 0.01;
        }
        if ($post['source'] == 1) { //如果是PC端
            if ($post['pay_style'] == 1) { //微信支付

                $orderInfo = [
                    'order_number' => $shop['out_trade_no'],
                    'total_price' => $shop['pay_money'],// 单位为元 ,最小为0.01
                    'order_type' => 3 //4表示支付小订单
                ];
                $notify = "https://api.globaltc.cn/api/notify/wxNotify";
                $res = wxpay($orderInfo, $notify);
                Db::commit();
                return writeJson(200, ['payInfo' => $res,'order_number'=>$orderInfo['order_number'],'total_price'=>$orderInfo['total_price']]);
            } elseif ($post['pay_style'] == 2) { //支付宝支付
                try {
                    $config = require_once ALI_PATH . "webaliconfig.php";
//                    $config['notify_url'] = $config['notify_url']."?source=1&&order_type=1";
                    $info = [
                        'body' => '网站支付',
                        'subject' => '测试支付宝电脑网站支付',
                        'order_no' => $shop['out_trade_no'],
                        'timeout_express' => time() + 600,// 表示必须 600s 内付款
                        'amount' => $shop['pay_money'],// 单位为元 ,最小为0.01
                        'return_param' => '1_3', //1表示PC支付 3表示商家支付
                        'goods_type' => '0',// 0—虚拟类商品，1—实物类商品
                        'store_id' => '',
                        'qr_mod' => '',
                    ];
                    $res = Charge::run("ali_web", $config, $info);
//                    $res = urldecode($res);
                    Db::commit();
                    return writeJson(200, ['payInfo' => $res]);
                } catch (PayException $e) {
                    Db::rollback();
                    throw new FailedException(['msg' => $e->errorMessage()]);
                }
            }
        } elseif ($post['source'] == 2) {
            if ($post['pay_style'] == 1) { //APP微信支付
                $config = require_once PAY_PATH . 'wxappconfig.php';
                $payData = [
                    'body'    => '用户充值',
                    'subject'    => '用户充值',
                    'order_no'    => $shop['out_trade_no'],
                    'timeout_express' => time() + 600,// 表示必须 600s 内付款
                    'amount'    => $shop['pay_money'],// 微信沙箱模式，需要金额固定为3.01
                    'return_param' => '2_3',
                    'client_ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1',// 客户地址
                ];
                try {
                    $res = Charge::run("wx_app",$config,$payData);
                    Db::commit();
                    return writeJson(200,['payInfo'=>$res]);
                } catch (PayException $e) {
                    Db::rollback();
                    throw new FailedException(['msg'=>$e->errorMessage()]);
                }
            } elseif ($post['pay_style'] == 2){ //支付宝支付
                try {
                    $config = require_once ALI_PATH . "aliconfig.php";
                    $info = [
                        'body' => '万享集',
                        'subject' => '商家付款',
                        'order_no' => $shop['out_trade_no'],
                        'amount' => $shop['pay_money'],
                        'return_param' => '2_3',

                    ];
                    $config['notify_url'] = "https://api.globaltc.cn/api/notify/shopAliNotify";
                    $res = Charge::run("ali_app", $config, $info);
                    Db::commit();
                    return writeJson(200, ['payInfo' => $res]);
                } catch (PayException $e) {
                    Db::rollback();
                    throw new FailedException(['msg' => $e->errorMessage()]);
                }
            }
            Db::commit();
            return writeJson(200);
        }
    }
}